package loghub

import (
	"fmt"
	"time"

	"gddgame.cc/galaxy/utils"
	sls "github.com/aliyun/aliyun-log-go-sdk"
	"github.com/aliyun/aliyun-log-go-sdk/producer"
	"github.com/gogo/protobuf/proto"
)

// https://github.com/aliyun/aliyun-log-go-sdk/blob/master/client.go
type Recorder struct {
	producer *producer.Producer
}

func NewRecorder(endPoint string, accessKeyId string, accessKeySecret string) *Recorder {
	recorder := &Recorder{}
	producerConfig := producer.GetDefaultProducerConfig()
	producerConfig.Endpoint = endPoint
	producerConfig.AccessKeyID = accessKeyId
	producerConfig.AccessKeySecret = accessKeySecret
	producerInstance := producer.InitProducer(producerConfig)

	recorder.producer = producerInstance
	producerInstance.Start()
	return recorder
}

func (recorder *Recorder) Send(topic string, data map[string]interface{}, message string) {
	content := []*sls.LogContent{}
	project := ""
	sub := ""
	ip := ""
	for key, value := range data {
		if key == "topic" {
			continue
		}
		if key == "project" {
			project = utils.ToString(value)
			continue
		}
		if key == "sub" {
			sub = utils.ToString(value)
			continue
		}
		if key == "ip" {
			ip = utils.ToString(value)
			continue
		}
		content = append(content, &sls.LogContent{
			Key:   proto.String(key),
			Value: proto.String(utils.ToString(value)),
		})
	}
	content = append(content, &sls.LogContent{
		Key:   proto.String("message"),
		Value: proto.String(message),
	})
	if err := recorder.producer.SendLog(project, sub, topic, ip, &sls.Log{
		Time:     proto.Uint32(uint32(time.Now().Unix())),
		Contents: content,
	}); err != nil {
		fmt.Println(err)
	}
}
